package edu.ufrj.pesc.pdfsearch;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

public class PDFSearchParser {
	
	public class ParsedPDF{
		private String content;
		private String isbn;
		private Metadata md;

		public ParsedPDF() {
			md = new Metadata();
			content = new String();
			isbn = new String();
		}
		
		public ParsedPDF(Metadata _md, String _content, String _isbn) {
			md = _md;
			content = _content;
			isbn = _isbn;
		}
		
		public String getContent() {
			return content;
		}

		public void setContent(String content) {
			this.content = content;
		}

		public String getIsbn() {
			return isbn;
		}

		public void setIsbn(String isbn) {
			this.isbn = isbn;
		}

		public Metadata getMd() {
			return md;
		}

		public void setMd(Metadata md) {
			this.md = md;
		}

	}
	
	static final Pattern isbnPattern = Pattern.compile("\\bISBN[^A-Z0-9]*+(\\d(?:-*+\\d){12})", Pattern.CASE_INSENSITIVE );

	/**
	 * constructor
	 */
	public PDFSearchParser() {

	}

	/**
	 * Process a single pdf file
	 * @param f File to be processed
	 */
	public ParsedPDF processFile(File f) {
		InputStream is = null;
		StringWriter writer = new StringWriter();
		Metadata md = new Metadata();
		
        try {
        	is = new BufferedInputStream(new FileInputStream(f));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
            
        Parser parser = new AutoDetectParser();
        ContentHandler handler = new BodyContentHandler(writer);
            
        try {
        	parser.parse(is, handler, md, new ParseContext());
		} catch (IOException | SAXException | TikaException e) {
			e.printStackTrace();
		}
            
        String content = writer.toString();
        String isbn = fetchISBN(content);
            
        return new ParsedPDF(md,content,isbn);
    }
    
    /**
	 * Parse the content of a PDF Book looking for its ISBN Number
	 * @param content String to be processed
	 * static final Pattern isbnPattern = Pattern.compile("\\bISBN[^A-Z0-9]*+(\\d(?:-*+\\d){12})", Pattern.CASE_INSENSITIVE );
	 */
    public static String fetchISBN(String content) {

    	Matcher m = isbnPattern.matcher(content); 
    	return m.find() ? m.group(1) : "";
    }
}
